import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

  constructor(public http: Http) { }
  // 消息提醒列表
    messageLists(params): Observable<any> {
        return this.http.get(ROOT_URL + 'News/index', {params})
            .map(this.extractData)
            .catch(this.handleError);
    }
    // 删除消息
    deleteMessage(params): Observable<any> {
        return this.http.put(ROOT_URL + 'News/delete', params )
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        const body = res.json();
        if (body['code'] === 5003) {
            alert('账号在其他设备登录');
            localStorage.token = '';
            localStorage.tokenTime = '';
            // window.location.reload();
        }
        return body;
    }
    private handleError (error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }


}
